<?php

namespace Modules\Shop\Models;

use Stancl\Tenancy\Database\Concerns\BelongsToTenant;
use App\Models\BaseModel;
use App\Traits\HasCreateBy;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletes;

/**
 * Class Spu.
 *
 * @package namespace Modules\Shop\Models;
 */
class Spu extends BaseModel
{
    use BelongsToTenant;
    use HasCreateBy, SoftDeletes;

    CONST TYPE_SINGLE = 1;
    CONST TYPE_MULTIPLE = 2;

    CONST PAY_TYPE_ONLINE = 1;
    CONST PAY_TYPE_OFFLINE = 2;
    CONST PAY_TYPE_ALL = 3;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $table = 'shop_spus';
    protected $fillable = [
        'uid', 'brand_id', 'category_id', 'status', 'name', 'description', 'unit', 'thumb', 'pay_type',
        'pic_url','create_by','type','spec_id','deduct_stock_type', 'content', 'delivery_id'
    ];

    /**
     * The attributes that are can be search =/like.
     *
     * @var array
     */
    protected $fieldSearchable = [];
    public static $types = [
        self::TYPE_SINGLE => '单规格',
        self::TYPE_MULTIPLE => '多规格'
    ];
    public static $pay_types = [
        self::PAY_TYPE_ONLINE => '在线支付',
        self::PAY_TYPE_OFFLINE => '货到付款',
        self::PAY_TYPE_ALL => '在线支付/货到付款'
    ];

    public function openOrgFilter()
    {
        return false;
    }

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($model) {
            $model->uid = $model->uid ?? self::getRandomNumber('uid', $model->category->id);
        });

        // 过滤tenant_id
        static::addGlobalScope('tenant_id', function (Builder $builder){
            $_tenant_id = tenant('id');
            $tenant_ids = SpuExtend::where('tenant_id', $_tenant_id)->get()->pluck('product_id');
            $builder->where('tenant_id', $_tenant_id)->orWhereIn('uid', $tenant_ids);
        });
    }

    /**
     * 跨组织商品选品
     *
     * @param [type] $query
     * @return void
     */
    public function scopePick($query)
    {
//        $parentOrg = auth()->org()->getParents(false);
//        $exists = SpuExtend::where('tenant_id', auth()->tenant())->get()->pluck('product_id');
//        return $query->withoutGlobalScope('tenant_id')->whereIn('tenant_id', $parentOrg->pluck('tenant_id'))->whereNotIn('uid',$exists);
        return $query->withoutGlobalScope('tenant_id');
    }

    /**
     * 品牌
     *
     * @return void
     */
    public function brand()
    {
        return $this->hasOne('Modules\Shop\Models\Brand', 'id', 'brand_id');
    }

    /**
     * 类别
     *
     * @return void
     */
    public function category()
    {
        return $this->hasOne('Modules\Shop\Models\Category', 'id', 'category_id');
    }

    /**
     * sku
     *
     * @return void
     */
    public function sku()
    {
        return $this->hasMany('Modules\Shop\Models\Sku', 'product_id', 'uid');
    }

    /**
     * 规格
     *
     * @return void
     */
    public function spec()
    {
        return $this->hasOne('Modules\Shop\Models\Spec', 'id', 'spec_id')->with('vals');
    }


    public function openShop()
    {
        return $this->hasOne('Modules\OpenShop\Models\OpenShopProduct', 'product_id', 'uid');
    }

    /**
     * 获得规格和sku
     *
     * @param [type] $spec_id
     * @param integer $product_id
     * @return void
     */
    public static function getSpecData($spec_id = '', $product_id = '')
    {
        $data = [
            'attr' => [],
            'list' => []
        ];
        $spu = $product_id ? self::where('uid', $product_id)->first() : new self();

        $spec = Spec::withoutGlobalScope('tenant_id')->find($product_id?$spu->spec_id:$spec_id);
        if(!$spec) {
            return $data;
        }
        $data['attr'] = $spec->getValOptions();

        if($product_id > 0) {
            $data['list'] = $spu->sku->map(function($sku) {
                return [
                    'spec_val_ids' => $sku->specVals->implode('id', ',').'',
                    'form' => [
                        'readonly' => true,
                        'uid'=> $sku->uid,
                        'market_price_fee' => $sku->market_price_fee,
                        'price_fee'=> $sku->price_fee,
                        'stock'=> $sku->stock,
                        'weight'=> $sku->weight,
                    ]
                ];
            })->toArray();
        }

        return $data;
    }

    /**
     * 继承商品
     *
     * @param [type] $tenant_id
     * @param array $product_ids
     * @return void
     */
    public static function extendToOrg($tenant_id, array $product_ids)
    {
        foreach($product_ids as $_spu) {
            SpuExtend::updateOrCreate([
                'tenant_id' => $tenant_id,
                'product_id' => $_spu
            ]);
        }
        return true;
    }
}
